package com.wr.modules.file.service.impl;

import cn.mybatis.mp.core.mvc.impl.DaoImpl;
import com.wr.common.core.constants.ServerNameConstants;
import com.wr.common.core.exception.ServiceException;
import com.wr.common.core.utils.BeanUtils;
import com.wr.common.core.utils.StringUtils;
import com.wr.common.core.utils.uuid.IdUtils;
import com.wr.modules.file.common.constants.FileConstants;
import com.wr.modules.file.common.utils.FileTypeUtils;
import com.wr.modules.file.common.utils.FileUploadUtils;
import com.wr.modules.file.domain.sys.file.SysFile;
import com.wr.modules.file.domain.sys.file.SysFileVo;
import com.wr.modules.file.mapper.SysFileMapper;
import com.wr.modules.file.service.ISysFileService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * @author MyPC
 */
@Service
public class SysFileServiceImpl extends DaoImpl<SysFile, String> implements ISysFileService {

    @Autowired
    private FileConstants fileConstants;
    @Resource
    private SysFileMapper sysFileMapper;

    @Override
    public SysFileVo uploadFile(MultipartFile file) {
        if (StringUtils.isNull(file)) {
            throw new ServiceException("文件参数为空，请选择文件");
        }
        String oldName = file.getOriginalFilename();
        String newName = "";
        try {
            newName = FileUploadUtils.upload(fileConstants.getPath(), file);
        } catch (IOException e) {
            throw new ServiceException("文件上传失败" + e);
        }
        String url = "/" + ServerNameConstants.IS_SERVER + fileConstants.getPrefix() + newName;
        SysFile sysFile = new SysFile();
        sysFile.setFileId(IdUtils.fastSimpleUuid());
        sysFile.setFileType(FileTypeUtils.getFileType(oldName));
        sysFile.setUploadType(ServerNameConstants.IS_SERVER);
        sysFile.setOldName(oldName);
        sysFile.setNewName(newName);
        sysFile.setFileSuffix(FileTypeUtils.getExtension(file));
        sysFile.setAbsolutePath(fileConstants.getPath() + newName);
        sysFile.setRelativePath(url);
        sysFile.setCreateTime(new Date());
        if (sysFileMapper.save(sysFile) > 0) {
            return BeanUtils.copyDataProp(sysFile, new SysFileVo());
        } else {
            throw new ServiceException("文件上传失败");
        }
    }
}
